<!DOCTYPE html>
<!--
  ~ Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
  ~
  ~ Copyright (C) 2019 THL A29 Limited, a Tencent company.  All rights reserved.
  ~
  ~ BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
  ~
  ~ A copy of the MIT License is included in this file.
  ~
  ~
  ~ Terms of the MIT License:
  ~ ---------------------------------------------------
  ~ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  -->

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="<%=htmlWebpackPlugin.options.urlPrefix %>/console/static/favicon.ico" type="image/x-icon" />
    <link rel="shortcut icon" href="<%=htmlWebpackPlugin.options.urlPrefix %>/console/static/favicon.ico" type="image/x-icon" />
    <link rel='preload' as='script' href="<%=htmlWebpackPlugin.options.urlPrefix %>/console/static/vue.min.js" />
    <link rel='preload' as='script' href="<%=htmlWebpackPlugin.options.urlPrefix %>/console/static/vuex.min.js" />
    <link rel='preload' as='script' href="<%=htmlWebpackPlugin.options.urlPrefix %>/console/static/vue-router.min.js" />
    
    <!-- devops:preload -->
    <% for (key in htmlWebpackPlugin.files.js) { %>
        <link href="<%= htmlWebpackPlugin.files.js[key] %>" as="script" rel="preload" />
    <% } %>
    <!-- end devops:preload -->

    <!-- devops:css -->
    <% for (key in htmlWebpackPlugin.files.css) { %>
        <link href="<%= htmlWebpackPlugin.files.css[key] %>" rel="stylesheet" />
    <% } %>
    <!-- end devops:css -->
    <title>蓝盾DevOps平台</title>
</head>
<body>
    <script>
            var ajax = new XMLHttpRequest();
            ajax.open("GET", "<%=htmlWebpackPlugin.options.urlPrefix %>/svg-sprites/devops_sprite.svg?t=" + Math.random(), true)
            ajax.send();
            ajax.onload = function(e) {
                var div = document.createElement('div');
                div.setAttribute("style", "position: absolute; width: 0; height: 0")
                div.innerHTML = ajax.responseText
                document.body.insertBefore(div, document.body.childNodes[0]);
            }
    </script>
    <div id="devops-root">
        <div class="bk-loading" style="position: absolute;">
            <div class="bk-loading-wrapper">
                <div class="bk-loading1">
                <div class="point point1"></div>
                <div class="point point2"></div>
                <div class="point point3"></div>
                <div class="point point4"></div>
            </div>
            <div class="bk-loading-title"></div>
        </div>
    </div>
    </div>
    <script src="<%=htmlWebpackPlugin.options.urlPrefix %>/console/static/vue.min.js"></script>
    <script src="<%=htmlWebpackPlugin.options.urlPrefix %>/console/static/vuex.min.js"></script>
    <script src="<%=htmlWebpackPlugin.options.urlPrefix %>/console/static/vue-router.min.js"></script>
    <!-- devops:assets -->
    <!-- end devops:assets -->
    
    <script>
        var WEBSITE_URL = '__HTTP_SCHEMA__://__BKCI_FQDN__'
        var GW_URL_PREFIX = '__HTTP_SCHEMA__://__BKCI_FQDN__/ms'     // api接口前缀
        var WS_URL_PREFIX = '__HTTP_SCHEMA__://__BKCI_FQDN__/'
        var PERM_URL_PREFIX = '__HTTP_SCHEMA__://__PAAS_FQDN__:__PAAS_HTTPS_PORT__/o/bk_iam_app' // EE PERM URL PREFIX
        var DOCS_URL_PREFIX = '__HTTP_SCHEMA__://__BKCI_IWIKI_FQDN__'  // 文档中心域名
        var LOGIN_SERVICE_URL = '__LOGIN_SERVICE_URL__'
        var DEVOPS_LS_VERSION = '<%- htmlWebpackPlugin.options.DEVOPS_LS_VERSION%>'
        var ENTERPRISE_VERSION = false
    </script>
    
    
    <script>
        var X_DEVOPS_PROJECT_ID = 'X-DEVOPS-PROJECT-ID'
        // 动态加载js
        function importScript (src, oHead, fOnload) {
            var oScript = document.createElement('script')
            oScript.type = 'text\/javascript'
            
            if (fOnload) { 
                oScript.onload = fOnload
            }
            
            oScript.setAttribute('src', src)
            oScript.setAttribute('defer', '')
            oHead.appendChild(oScript)
        }

        // 动态加载css
        function importStyle (href, oHead) {
            var oStyle = document.createElement('link')
            oStyle.setAttribute('rel', 'stylesheet')
            oStyle.setAttribute('type', 'text/css')
            oStyle.setAttribute('href', href)
            oHead.appendChild(oStyle)
        }

        function isValidPid (projectList, pid) {
            for(var i = 0; i < projectList.length; i++) {
                var proj = projectList[i]
                if (proj.projectCode === pid) {
                    return true
                }
            }
            return false
        }
        
        for ( var i = 0; i < window.jsAssets.length; i++ ) {
            var js = window.jsAssets[i]
            if (js.indexOf('vendors') > -1) {
                importScript(js, document.body)
            }
        }

        function getCookie(cname) {
            try {
                var name = cname + "=";
                var decodedCookie = decodeURIComponent(document.cookie);
                var ca = decodedCookie.split(';');
                for(var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') {
                        c = c.substring(1);
                    }
                    if (c.indexOf(name) == 0) {
                        return c.substring(name.length, c.length);
                    }
                }
                return '';
            } catch (e) {
                console.error('get cookie error', e.message)
                return ''
            }
        }

        function setCookie(cname, cvalue, domain){
            document.cookie = cname + "=" + cvalue + "; " + 'domain=' + domain + '; path=/';
        }
        
        window.setProjectIdCookie = function (projectId) {
            try {
                if (projectId) {
                    setCookie(X_DEVOPS_PROJECT_ID, '', location.host)
                    setCookie(X_DEVOPS_PROJECT_ID, projectId, location.host)
                    window.GLOBAL_PID = projectId
                }
            } catch (e) {
                console.warn('you have no project')
            }
        }

        function matchPathProjectId () {
            try {
                var reg = /^\/console\/\w+\/([\w\-]+)?/
                if (location.pathname.match(/^\/console\/perm\/(\w+)?/)){
                    var query = location.search.slice(1)
                    var queryArr = query.split('&')
                    for(var i = 0; i < queryArr.length; i++) {
                        var item = queryArr[i].split('=')
                        var key = decodeURIComponent(item[0])
                        if (key === 'projectCode') {
                            return decodeURIComponent(item[1])
                        } 
                    }
                    return ''    
                }else if (location.pathname.match(/^\/console\/store\/(\w+)?/)){ // TODO store没有projectId
                    return ''    
                } else {
                    var res = location.pathname.match(reg)
                    return res ? res[1] : ''
                }
                
            } catch (e) {
                console.warn(e)
                return ''
            }
        }

        var pathPid = matchPathProjectId() || getCookie(X_DEVOPS_PROJECT_ID)
        window.setProjectIdCookie(pathPid)
        
    </script>
    <script>
        
        window.getLoginUrl = function () {
            var c_url = location.origin + location.pathname + encodeURIComponent(location.search)
            if (/=%s/.test(LOGIN_SERVICE_URL)) { 
                return LOGIN_SERVICE_URL.replace(/%s/, c_url)
            } else if (/\?/.test(LOGIN_SERVICE_URL)) { 
                LOGIN_SERVICE_URL =  LOGIN_SERVICE_URL + '&c_url=' + c_url
            } else {
                return LOGIN_SERVICE_URL =  LOGIN_SERVICE_URL + '?c_url=' + c_url
            }
            return LOGIN_SERVICE_URL
        }

        function asyncGet (url, pid) {
            return new Promise(function (resolve, reject) {
                var xhr = new XMLHttpRequest()
                xhr.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        var res = JSON.parse(xhr.responseText)
                        resolve(res && res.data ? res.data : res )
                    }  else if (this.status == 401) {
                        // 无登录，这里处理跳转逻辑
                        window.location.href = window.getLoginUrl()
                    } else if (this.readyState == 4 && this.status > 400) {
                        reject({
                            status: this.status,
                            message: this.status === 503 ? '服务维护中，请稍候...' : '服务器内部异常'
                        })
                    }
                }
                
                xhr.withCredentials = true
                xhr.open('GET', url)
                pid && xhr.setRequestHeader(X_DEVOPS_PROJECT_ID, pid)
                xhr.send()
            })
        }

        function fetchAllServices () {
            return asyncGet(GW_URL_PREFIX + '/project/api/user/services/', pathPid)
        }

        function fetchAssetsJSON () {
            return asyncGet('/assets_bundle.json?t=' + Math.random())
        }

        function fetchAllProjects () {
            return asyncGet(GW_URL_PREFIX + '/project/api/user/projects/')
        }

        function requestUser () {
            return asyncGet(GW_URL_PREFIX + '/project/api/user/users')
        }

        function joinUrl (urlArr) {
            if (Array.isArray(urlArr)) {
                return urlArr.join('/').replace(/([^:]\/)\/+/g, '$1')
            }
            return ''
        }


        function getServiceObject (serviceList, assetsJSON) {
            var serviceMap = {}
            var iframeRoutes = []
            for (var i = 0; i < serviceList.length; i++) {
                var children = serviceList[i].children
                for (var j = 0; j < children.length; j++) {
                    var mod = children[j].link_new.replace(/^\/?(\w+)\S*/, '$1')
                    var serviceTitle = children[j].name.replace(/\(\S+?\)/, '')
                    var assetMod = assetsJSON[mod]
                    if (children[j].inject_type === 'amd') {
                        var jsUrl = assetMod ? joinUrl([ mod, assetMod.js ]) : children[j].js_url
                        var cssUrl = assetMod ? joinUrl([ mod, assetMod.css ]) : children[j].css_url
                        children[j].js_url = joinUrl([ WEBSITE_URL, jsUrl ])
                        children[j].css_url = joinUrl([ WEBSITE_URL, mod, cssUrl ])
                    } else {
                        children[j].iframe_url = joinUrl([ WEBSITE_URL, children[j].iframe_url ])
                    }
                    serviceMap[mod] = children[j]
                    if (children[j].inject_type === 'iframe') {
                        iframeRoutes.push({
                            path: mod + (children[j].show_project_list ? '/:projectId?' : ''),
                            name: mod,
                            meta: {
                                showProjectList: children[j].show_project_list,
                                showNav: children[j].show_nav,
                                projectIdType: children[j].project_id_type,
                                header: typeof mod === 'string' ? mod.toLowerCase() : serviceTitle,
                                title: serviceTitle,
                                logo: mod,
                                webSocket: (children[j].webSocket || '').split(',')
                            }
                        })
                    }
                }
            }
            return {
                serviceMap: serviceMap,
                iframeRoutes: iframeRoutes
            }
        }

        function getDefaultPid (projectList) {
            if (Array.isArray(projectList) && projectList.length > 0) {
                var firstProj = projectList[0]
                var firstPid = firstProj && firstProj.projectCode ? firstProj.projectCode : undefined
                for(var i = 0; i < projectList.length; i++) { 
                    var proj = projectList[i]
                    if (proj && !proj.gray) {
                        return proj.projectCode
                    }
                }
                if (firstPid) {  // 如果cookie为空，而项目列表中找不到非灰度的项目时，将cookie值设置为首个项目id, 同时自动刷新页面
                    window.setProjectIdCookie(firstPid)
                    location.reload()
                }
            }

        }

        function init (projectList, allServices, userInfo, assetsJSON) {
            var path = location.pathname.replace('/console', '')
            var headTag = document.head || document.getElementsByTagName('head')[0]
            var pathReg = /^\/(\w+)\/?/
            var serviceObject = getServiceObject(allServices, assetsJSON)
            var serviceMap = serviceObject.serviceMap
            var serviceMatchResult = path.match(pathReg)
            var subServiceId = serviceMatchResult ? serviceMatchResult[1] : null
            var page = serviceMap[subServiceId] || null
            var isPidOk = isValidPid(projectList, pathPid)
            if (!isPidOk && !pathPid) {
                var defaultPid = getDefaultPid(projectList)
                window.setProjectIdCookie(defaultPid)
            }


            window.allServices = allServices
            window.serviceObject = serviceObject
            window.currentPage = page
            window.projectList = projectList
            
            userInfo.isAuthenticated = true
            window.userInfo = userInfo
            
            if (page && page.inject_type === 'amd') {
                var inject_type = page.inject_type
                var js_url = page.js_url
                var css_url = page.css_url
                var title = page.title

                importScript(js_url, document.body, loadJsAssets)
                importStyle(css_url, headTag)
            }else {
                loadJsAssets()
            }
        }
        
        
        var CACHE_PREFIX = '_cache_'
        window.setLsCacheItem = function (key, value) {
            try {
                if (key && typeof key === 'string') {
                    var cacheKey = CACHE_PREFIX + key
                    localStorage.setItem(cacheKey, JSON.stringify(value))
                }
            } catch (error) {
                console.warn(error)
            }

        }

        window.getLsCacheItem = function (key) {
            if (key && typeof key === 'string') {
                var cacheKey = CACHE_PREFIX + key
                var cacheJson = localStorage.getItem(cacheKey)
                try {
                    return JSON.parse(cacheJson)
                } catch (e) {
                    return null
                }
            }
        }

        function fetchData() {
            return Promise.all([
                fetchAllProjects(),
                fetchAllServices(),
                requestUser(),
                fetchAssetsJSON()
            ]).then(response => {
                console.log(response)
                var cahceArray = [ 'projectList', 'allServices', 'userInfo' ]
                var actionArray = [ 'setProjectList', 'setServices', 'setUserInfo' ]
                for(var i = 0; i < cahceArray.length; i++) {
                    if (window.vuexStore && typeof window.vuexStore.dispatch === 'function') {
                        window.vuexStore.dispatch(actionArray[i], response[i])
                    }
                    window.setLsCacheItem(cahceArray[i], response[i])
                }
                return response
            })
        }

        function getData () {
            return new Promise((resolve, reject) => {
                var projectList = window.getLsCacheItem('projectList')
                var allServices = window.getLsCacheItem('allServices')
                var userInfo = window.getLsCacheItem('userInfo')
                
                fetchData().then(response => {
                    resolve(response)
                }).catch(e => {
                    console.error(e)
                    if (projectList && allServices && userInfo) {
                        resolve([ projectList, allServices, userInfo ])
                        return
                    }

                    reject(e)
                }) 
            })
        }

        getData().then(response => {
            init(...response)
        }).catch(function (e) {
            console.log(e)
            printError(e.status, e.message)
        })  
        

        function printError (status, msg) {
            document.writeln(
                '<div style="height: 100%; width: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column;">' 
                + '<img src="/console/static/' + status + '.png" />'
                + '<p style="font-size: 20px; color: #979797; margin: 32px 0;">' + msg + '</p>'
                + '</div>'
            )
        }

        function loadJsAssets () {
            for ( var i = 0; i < window.jsAssets.length; i++ ) {
                var js = window.jsAssets[i]
                if (js.indexOf('vendors') === -1) {
                    importScript(js, document.body)
                }
            }
        }
        
        function handleVisibilityChange () {
            if (!document.hidden && window.GLOBAL_PID) {
                window.setProjectIdCookie(window.GLOBAL_PID)
            }
        }

        (function () {
            document.addEventListener('visibilitychange', handleVisibilityChange, false);
        })();

        window.onbeforeunload = function () {
            document.removeEventListener('visibilitychange', handleVisibilityChange, false);
        }
    </script>
</body>
</html>